//
//  ZCPreLiveViewController.m
//  ZCLive
//
//  Created by 彭军 on 2017/11/12.
//  Copyright © 2017年 Elvis. All rights reserved.
//
#import <CCClassRoom/CCStreamer.h>
#import "ZCPreLiveViewController.h"
#import "ZCLiveViewController.h"
#import "UIAlertView_Block.h"
#import "ZLDefine.h"
#import "NLBaseNC.h"
#import "ZCRoomInfoModel.h"
#import "NSString+TitleSize.h"
#import "ZCPreTipsView.h"
@interface ZCPreLiveViewController ()
@property (strong, nonatomic) UIView *innerView;
@property (strong, nonatomic) UIActivityIndicatorView *activityIndicatorView;
@property (strong, nonatomic) NSString *roomId;
@property (strong, nonatomic) NSString *userId;
@property (assign, nonatomic) BOOL isLogin;
@property (strong, nonatomic) ZCLiveViewController *liveVC;
@property (weak, nonatomic) NSTimer *timer;
@property (strong, nonatomic) NSURLSessionDataTask *sessionDataTask;
@property (strong, nonatomic) UILabel *loadingLbl;
@property (strong, nonatomic) UIAlertView *alertView;
@property (strong, nonatomic) UIButton *kefuBtn;
@end

@implementation ZCPreLiveViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"视频查勘";
    self.imageView.image = [UIImage imageNamed:KZCBundleImg(@"zc_kongxian")];
    self.startLiveBtn.layer.masksToBounds = YES;
    self.startLiveBtn.layer.cornerRadius = 38/2;
    [self.startLiveBtn addTarget:self action:@selector(startLiveAction:) forControlEvents:UIControlEventTouchUpInside];

    self.kefuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.kefuBtn setImage:[UIImage imageNamed:KZCBundleImg(@"zc_kefu")] forState:UIControlStateNormal];
    self.kefuBtn.frame = CGRectMake(SCREEN_WIDTH - 43 - 14, 14, 43, 43);
    [self.view addSubview:self.kefuBtn];
    [self.kefuBtn addTarget:self action:@selector(callPhone) forControlEvents:UIControlEventTouchUpInside];
    
    _innerView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _innerView.backgroundColor = [[UIColor alloc] initWithRed:0 green:0 blue:0 alpha:0.2];
    _innerView.hidden = YES;
    [self.view addSubview:_innerView];
    
    _activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    _activityIndicatorView.center = self.view.center;
    [_activityIndicatorView startAnimating];
    [_innerView addSubview:_activityIndicatorView];
    
    _loadingLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, _activityIndicatorView.frame.origin.y+50, SCREEN_WIDTH, 20)];
    _loadingLbl.text = @"正在获取坐席，请稍后...";
    _loadingLbl.textColor = [UIColor whiteColor];
    _loadingLbl.textAlignment = NSTextAlignmentCenter;
    [_innerView addSubview:_loadingLbl];
    self.view.backgroundColor = NLColorFromRGB(0xF2F2F6);
    
    [self.startLiveBtn setBackgroundColor:NLColorFromRGB(0xFD8736)];
    self.startLiveBtn.userInteractionEnabled = NO;
   
    
    [self setBackBarItem];
    
    [self updateUIWithSuccess:NO];
}


/**
 查询坐席是否空闲
 */
-(void)loopSearchStatus{

     NSString *urlString = [NSString stringWithFormat:@"%@/remote/isWebStatus?phone=%@&licenseNo=%@",ZCHTTP,self.phoneNum,self.cartId];
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    // 2.创建一个网络请求
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    // 3.获得会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    // 4.根据会话对象，创建一个Task任务：
    __weak typeof(self) weakSelf = self;
    self.sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.innerView.hidden = YES;
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if (httpResponse.statusCode == 200) {
                
                [weakSelf loopSuccess:data];
                
            }else{
                
               [weakSelf loopFailed:data];
            }
        });
        
    }];
    // 5.最后一步，执行任务（resume也是继续执行）:
    [self.sessionDataTask resume];
    
    
}

-(void)loopSuccess:(NSData *)data{
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
    
    if (dict && dict.count) {
    
        NSDictionary *statusData = [dict objectForKey:@"data"];
        
        NSNumber *status = [statusData objectForKey:@"status"];
        if (status.integerValue==1) {
            [self stopTimer];
            [self updateUIWithSuccess:YES];
            
        }else{
            [self startTimer];
            [self updateUIWithSuccess:NO];
        }
    }else{
        [self startTimer];
        [self updateUIWithSuccess:NO];
    }
}

-(void)loopFailed:(NSData *)data{
    [self startTimer];
    [self updateUIWithSuccess:NO];
}

-(void)callPhone{
    if (self.roomInfo.phone.length) {
        NSString *phone=[[NSMutableString alloc] initWithFormat:@"tel:%@",self.roomInfo.phone];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phone]];
    }else{
        [ZCPreTipsView showTips:@"暂无号码！"];
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loopSearchStatus];
}

-(void)viewWillDisappear:(BOOL)animated{
    
    [self.timer invalidate];
    self.timer = nil;
    [self.sessionDataTask cancel];
}


- (void)setBackBarItem {
    UIImage *image = [UIImage imageNamed:KZCBundleImg(@"back")];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, image.size.width + 5, image.size.height);
    [backButton addTarget:self action:@selector(backButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [backButton setImage:image forState:UIControlStateNormal];
    backButton.imageEdgeInsets = UIEdgeInsetsMake(0, -18, 0, 0);
    backButton.contentMode = UIViewContentModeCenter;
    backButton.exclusiveTouch = YES;
    UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = backButtonItem;
}

-(void)backButtonAction{
    
    __weak typeof(self) weakSelf = self;
    [UIAlertView_Block initWithTitle:@"" message:@"确定退出？" cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确定"] clickAtIndex:^(NSInteger buttonIndex) {
        if (buttonIndex==1) {
            [UIApplication sharedApplication].idleTimerDisabled = NO;
            [weakSelf dismissViewControllerAnimated:YES completion:^{
                if (weakSelf.closeBlock) {
                    weakSelf.closeBlock(YES, nil);
                }
            }];
        }
    }];
    
   
}


-(void)startTimer{
    
    if (!self.timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:15.0 target:self selector:@selector(loopSearchStatus) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
}

-(void)stopTimer{
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

-(void)countDown{
    
    if (self.roomInfo && self.roomInfo.roomId.length && self.roomInfo.surveyId.length) {
        [self.timer invalidate];
        self.timer = nil;
    }else{
        if (self.sessionDataTask) {
            [self.sessionDataTask cancel];
        }
        [self loadData];
    }
    
}


-(void)startLiveAction:(id)sender{
    [self loadData];
}

-(void)gotoLiveVC{
    
    ZCLiveViewController *pushVC = [self.navigationController.viewControllers objectAtIndex:0];
    if ([pushVC isKindOfClass:[ZCLiveViewController class]]) {
        pushVC.isPreLive = YES;
        pushVC.roomInfo = self.roomInfo;
        [self.navigationController popToViewController:pushVC animated:YES];
    }else{
        pushVC = [[ZCLiveViewController alloc] init];
        pushVC.isPreLive = YES;
        pushVC.roomInfo = self.roomInfo;
        pushVC.phoneNum = self.phoneNum;
        pushVC.cartId = self.cartId;
        [self.navigationController popToViewController:pushVC animated:YES];
    }
}


-(void)loadData{
    
    _innerView.hidden = NO;
    NSString *urlString = [NSString stringWithFormat:@"%@/remote/liveApply?phone=%@&licenseNo=%@",ZCHTTP,self.phoneNum,self.cartId];
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    
    __weak typeof(self) weakSelf = self;
    self.sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.innerView.hidden = YES;
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if (httpResponse.statusCode == 200) {
                
                [weakSelf success:data];
                
            }else{
                
                [weakSelf failed:error];
            }
        });
        
    }];
    // 5.最后一步，执行任务（resume也是继续执行）:
    [self.sessionDataTask resume];
}


-(void)success:(NSData *)data{
    
    _innerView.hidden = YES;
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
    
    if (dict && dict.count) {
        
        NSString *code = [dict objectForKey:@"code"];
        NSString *msg = [dict objectForKey:@"msg"];
        NSDictionary *roomData = [dict objectForKey:@"data"];
        
        if ([code isEqualToString:@"0000"]) {
            [self stopTimer];
            self.roomInfo = [ZCRoomInfoModel yy_modelWithDictionary:roomData];
            [self gotoLiveVC];
            
        }else{
            if (roomData) {
                self.roomInfo = [ZCRoomInfoModel yy_modelWithDictionary:roomData];
            }
            [self updateUIWithSuccess:NO];
            [self startTimer];
            [ZCPreTipsView showTips:@"坐席繁忙！"];
        }
        
    }else{
        [self updateUIWithSuccess:NO];
        [self startTimer];
        [ZCPreTipsView showTips:@"坐席繁忙！"];
    }
    
}

-(void)failed:(NSError *)error{
    _innerView.hidden = YES;
    [self updateUIWithSuccess:NO];
    [self startTimer];
    [ZCPreTipsView showTips:@"坐席繁忙！"];
}


-(void)updateUIWithSuccess:(BOOL)isSuccess{
    
    if (isSuccess) {
        self.titleLbl.text = @"后台坐席空闲，请立即发起视频连线";
        self.tipsLbl.text = nil;
        self.imageView.image = [UIImage imageNamed:KZCBundleImg(@"zc_kongxian")];
        [self.startLiveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.startLiveBtn setBackgroundColor:NLColorFromRGB(0xFD8736)];
        self.startLiveBtn.userInteractionEnabled = YES;
    }else{
        self.titleLbl.text = @"后台坐席繁忙，请稍后";
        self.tipsLbl.text = @"系统自动排队中，后台坐席空闲后系统自动通知您进行连线，请稍后...";
        self.imageView.image = [UIImage imageNamed:KZCBundleImg(@"zc_fanmang")];
        [self.startLiveBtn setBackgroundColor:[UIColor whiteColor]];
        [self.startLiveBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        self.startLiveBtn.userInteractionEnabled = NO;
    }
    
}


-(BOOL)shouldAutorotate{
    
    return YES;
    
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    
    return UIInterfaceOrientationMaskPortrait;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

